#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "dictionary.h"
#include "rdictionary.h"

#define MAX_PART_SIZE 5

char *read_file(const char *);
void error(const char *);

int main(int argc, char *argv[])
{
    char *word_ptr, *input_buffer = read_file(argv[1]);

    char tmp[MAX_PART_SIZE + 1];
    tmp[MAX_PART_SIZE] = '\0';

    dict_init();
    rdict_init();

    word_ptr = strtok(input_buffer, ",");
    while (word_ptr != NULL) {
        dict_add(word_ptr);
        rdict_add(word_ptr);
        word_ptr = strtok(NULL, ",");
    }

    free(input_buffer);
    input_buffer = read_file(argv[1]);

    dict_debug_tree();

    dict_optimize();
    rdict_optimize();

    int len, word_index, i;

    word_ptr = strtok(input_buffer, ",");
    while (word_ptr != NULL) {
        len = strlen(word_ptr);
        for (i = 0; i < len; i += MAX_PART_SIZE)
        {
            strncpy(tmp, word_ptr + i, MAX_PART_SIZE);
            word_index = dict_search(tmp);
            if (word_index == -1)
                continue;
            dict_mark(word_index);
            rdict_mark(word_index);
            printf("%d of %d\n", rdict_mark_count, rdict_word_count);
        }
        word_ptr = strtok(NULL, ",");
    }

    free(input_buffer);
    dict_delete();
    rdict_delete();

    return 0;
}

char *read_file(const char *filename)
{
    FILE *fp;
    char *buffer;
    long size;

    fp = fopen(filename, "r");
    if (fp == NULL)
        error("Missing input file.");

    fseek(fp, 0, SEEK_END);
    size = ftell(fp);

    buffer = (char *) malloc(sizeof(char) * size);
    if (buffer == NULL)
        exit(1);

    rewind(fp);
    fread(buffer, sizeof(char), size, fp);
    fclose(fp);

    return buffer;
}

void error(const char *message)
{
    fprintf(stderr, "%s\n", message);
    exit(1);
}
